﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;

using SpectationClient.Stuff;
using SpectationClient.GUI;
using SpectationClient.DataBaseDescription;

namespace SpectationClient.DGVExtensions {




    public class DataGridViewPhotoColumn : DataGridViewExtensionBaseColumn {
       
        /// <summary>
        /// Set this to allow this column to reload photos from the data base.
        /// </summary>
        public Npgsql.NpgsqlConnection Connection { get; set; }
        
        private GUI.UC.ViewImageForm imageForm;


        public override TableInfo TableInfo {
            get { return this.ColumnInfo == null ? null: this.ColumnInfo.Table; }
        }

        protected new ColumnInfoImageFile columnInfo;
        public new ColumnInfoImageFile ColumnInfo {
            get {
                
                return this.columnInfo;
            }
        }

        public DataGridViewPhotoColumn() {
            init();
        }

        public DataGridViewPhotoColumn(ColumnInfoImageFile columnInfoImageFile, Npgsql.NpgsqlConnection connection) {
            this.columnInfo = columnInfoImageFile;
            this.Connection = connection;
            init();
        }

        private Boolean? isPreviewColumn = null;
        public Boolean IsPreviewColumn {
            get {
                checkPreviewColumn();
                return this.isPreviewColumn != null && this.isPreviewColumn == true;
            }
        
        }

        private void checkPreviewColumn() {
            if(isPreviewColumn != null) return;

            this.isPreviewColumn = false;
            this.previewColumn = null;

            if(this.columnInfo != null && this.columnInfo.previewImageFile != null){
                ColumnInfoImageFile CI = this.columnInfo;
                if(CI.previewImageFile == CI){
                    this.isPreviewColumn = true;
                    this.previewColumn = this;
                }else{
                    this.isPreviewColumn = false;
                    if(CI.mainImageFile != null && 
                       this.DataGridView.Columns.Contains(CI.previewImageFile.Name)){
                           this.previewColumn = this.DataGridView.Columns[CI.previewImageFile.Name] as DataGridViewPhotoColumn;
                    
                    }

                }

            }
            

        }

        private DataGridViewPhotoColumn previewColumn = null;
        public DataGridViewPhotoColumn PreviewColumn {
            get { return this.IsPreviewColumn? this : this.previewColumn; }
        }
        
        

        private void init() {
            this.CellTemplate = new DataGridViewPhotoCell();
            
            this.ReadOnly = true;
            this.ContextMenuStrip = new ContextMenuStrip();
            ToolStripMenuItem labelShow = new ToolStripMenuItem("Bild anzeigen");
            ToolStripMenuItem labelSave = new ToolStripMenuItem("Bild(er) speichern");
            ToolStripMenuItem labelSet  = new ToolStripMenuItem("Bild ändern/einfügen");
           
            labelShow.Width = 150;
            labelSave.Width = 150;
            
            labelShow.Click += new EventHandler(labelShow_Click);
            labelSave.Click +=new EventHandler(labelSave_Click);
            labelSet.Click +=new EventHandler(labelSet_Click);
            this.ContextMenuStrip.Items.Add(labelShow);
            this.ContextMenuStrip.Items.Add(labelSave);
            this.ContextMenuStrip.Items.Add(labelSet);
        }

        void labelSet_Click(object sender, EventArgs e) {
            List<FileInfo> files = FormHelper.getPhotoFileInfos(false, "Bitte Foto angeben");
            if(files.Count > 0) {
                DataGridViewPhotoCell cell = this.getSelectedCell() as DataGridViewPhotoCell;
                if(cell != null) {
                    cell.setImage(files[0]);
                } 
            }

        }

        void labelSave_Click(object sender, EventArgs e) {
            List<DataGridViewCell> cells = getSelectedCells(true);
            SaveImagesDialog SID = new SaveImagesDialog(this.DataGridView);
            if(SID.ShowDialog() == DialogResult.OK) {
                this.DataGridView.Cursor = Cursors.WaitCursor;
                String folder = SID.Folder;
                ImageFormat format = SID.ImageFormat;
                String extension = "."+format.ToString().ToLower();
                bool useRowNumbers = SID.UseRowNumbers;
                String[] cols = SID.FileNameColumns;
                foreach(DataGridViewPhotoCell c in cells) {
                    String filename;
                    if(useRowNumbers) {
                        filename = String.Format("{0}{1}", this.Name, c.RowIndex+1);

                    } else {
                        String[] columnValues = (from String column in cols
                                                 let otherCell = this.DataGridView[column, c.RowIndex]
                                                 where otherCell.Value != null
                                                 select otherCell.Value.ToString()).ToArray();
                        filename = String.Format("{0}_{1}",
                                        this.Name,
                                        TextHelper.combine(columnValues, "_"));
                    }
                    filename = DataHelper.createNewFilePath(new FileInfo(SID.Folder + "\\"+ filename + extension)).FullName;
                    c.getImage().Save(filename, format);

                }
                this.DataGridView.Cursor = Cursors.Default;
                
            }
        }

        /// <summary>
        /// Opens a separat photo viewer and shows the first of all selected photos.
        /// </summary>
        public void showSelectedPhoto() {
            labelShow_Click(this.DataGridView, null);
        }

        void labelShow_Click(object sender, EventArgs e) {
            if(this.imageForm == null) {
                imageForm = new GUI.UC.ViewImageForm(this);
                if(sender != null) imageForm.Disposed += (sender1, e1) => this.imageForm = null;
                imageForm.Show();
            } else {
                imageForm.BringToFront();
            }
           
            
        }
    }
}
